package com.oscar.web.controller;


import com.oscar.web.domain.Book;
import com.oscar.web.domain.Users;
import com.oscar.web.service.RecommenderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.oscar.web.service.UsersService;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@Controller
public class UserController {

    @Autowired
    private UsersService usersService;

    @Autowired
    private RecommenderService recommenderService;

    // 获取实时推荐的图书
    @RequestMapping("/user/recommender")
    public ModelAndView getRateMoreProducts(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("personalized");
        String username = request.getUserPrincipal().getName() ;
        int userid = usersService.findByUsername(username).getUserId() ;
//        try {//try-catch进行捕获异常消息
//            userBookBuyService.buyBook(b);//把购买下消息传到server层进行处理
//        }catch (Exception e){//捕获巡行超时异常
//            msg = "数据走丢了，请稍后再试。。。" ;//反回异常消息
//        }
        List<Book> list = recommenderService.getStreamRecommendations(userid);
        mv.addObject("list",list);
        return mv;
    }

    @RequestMapping("/user/register")
    public ModelAndView register(String username, String password) {
        Users u = new Users();//新建对象，添加账号密码。
        u.setUsername(username);
        u.setPassword(password);

        ModelAndView mv = new ModelAndView("registerMsg") ;
        String msg = "" ;
        try {//try-catch进行捕获异常消息
            msg=usersService.saveUser(u);
        }catch (Exception e){//捕获巡行超时异常
            msg = "注册失败，请稍后再试。。。" ;//反回异常消息
        }
        mv.addObject("msg",msg);
        return mv;
    }
}